#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021-08-03 6:14 
# @Author : 李中华
# @Email  : 1260429766@qq.com
# @File : logger.py
import logging
from logging import handlers
import time
from ProjectPath import projectPath

'''日志封装
logger可以看做是一个记录日志的人，对于记录的每个日志，他需要有一套规则，比如记录的格式（formatter），等级（level）等等，
这个规则就是handler。使用logger.addHandler(handler)添加多个规则，就可以让一个logger记录多个日志。
'''
class Log(object):
    def setMSG(self,level,msg):
        format = logging.Formatter(fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s : %(message)s')
        logger = logging.getLogger()
        request_time = time.strftime('%Y%m%d',time.localtime(time.time()))
        filename = projectPath + '/resultreport/log/' + request_time + '.txt'
        '''
        when：是一个字符串，用于描述滚动周期的基本单位，字符串的值及意义如下：
        “S”: Seconds
        “M”: Minutes
        “H”: Hours
        “D”: Days
        “W”: Week
        day(0 = Monday)
        “midnight”: Roll
        over
        at
        midnight
        
        interval: 滚动周期，单位有when指定，比如：when =’D’, interval = 1，表示每天产生一个日志文件
        
        backupCount: 表示日志文件的保留个数
        '''
        fh = handlers.TimedRotatingFileHandler(filename=filename,when='D',interval=1,backupCount=7,encoding='utf-8')
        ch = logging.StreamHandler()
        # 定义日志输出格式
        fh.setFormatter(format)
        ch.setFormatter(format)
        #添加Handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        # 添加日志信息，输出INFO级别的信息
        logger.setLevel(logging.INFO)
        if level == "debug":
            logger.debug(msg)
        if level == "info":
            logger.info(msg)
        if level == "warning":
            logger.warning(msg)
        if level == "error":
            logger.error(msg)
        # 移除句柄，否则日志会重复输出
        logger.removeHandler(fh)
        logger.removeHandler(ch)
        fh.close()

    def debug(self,msg):
        self.setMSG('debug',msg)
    def info(self,msg):
        self.setMSG('info',msg)
    def warning(self,msg):
        self.setMSG('warning',msg)
    def error(self,msg):
        self.setMSG('error',msg)

if __name__ == '__main__':
    # t = time.time()
    # localtime = time.localtime(time.time())
    # print(localtime)
    Log().debug("debug测试")
    # Log().info("info测试")
    # Log().error("error测试")
